const express = require('express');
const router = express.Router();
const crypto = require('crypto');

const mysql = require('./../database');
const blogService = require('../service/blog_service')

//博客主页面
router.get('/article', function (req, res, next) {
  let query = 'SELECT * FROM article ORDER BY articleID DESC';
  mysql.query(query, function (err, rows, fields) {
    if (err) console.err(err);
    let articles = rows;
    articles.forEach(function (ele) {
      let year = ele.articleTime.getFullYear();
      let month = ele.articleTime.getMonth() + 1 > 10 ? ele.articleTime.getMonth() : '0' + (ele.articleTime.getMonth() + 1);
      let date = ele.articleTime.getDate() + 1 > 10 ? ele.articleTime.getDate() : '0' + ele.articleTime.getDate();
      ele.articleTime = year + '-' + month + '-' + date;
    });
    res.send(articles);
  });
});

//登录
router.get('/login', function (req, res, next) {
  console.log(req.session.user);
  res.send({ message: '', user: req.session.user });
});
router.post('/login', function (req, res, next) {
  // console.log(req.body)
  let name = req.body.user;
  let password = req.body.password;
  let verifyCode = req.body.verifycode;
  //密码MD5加密
  let hash = crypto.createHash('md5');
  hash.update(password);
  password = hash.digest('hex');
  // console.log('user：'+ name +",加密后的密码："+password);
  //mysql.escape(name)防止用户提交的数据里用Sql注入攻击
  let query = 'SELECT * FROM user WHERE userName=' + mysql.escape(name) + 'AND password=' + mysql.escape(password);
  mysql.query(query, function (err, rows, fields) {
    if (err) {
      //打印的内容均在服务器的命令行窗口中，不会在浏览器中打印
      console.log(err);
      return;
    }
    let user = rows[0];
    if (!user) {
      res.send({ message: '用户名或者密码错误', login: false });
      return;
    }
    // if (verifyCode != req.session.captcha) {
    //   res.render('login', { message: '验证码错误' });
    //   return;
    // }
    req.session.user = user;
    res.send({ login: true, user: req.session.user })
  });
});

router.post('/login', function (req, res, next) {
  let name = req.body.user;
  let password = req.body.password;
  let verifyCode = req.body.verifycode;
  (async () => {
    const result = await blogService.login(name,password,verifyCode);
    if (result) {

    } else {

    }
  })().then(res => {

  }).catch(err => {
    next(err);
  })
});

module.exports = router;